import 'dart:io';

import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'base_dio.dart';

const spProxyIp = "proxyIP"; // ip
const spProxyPort = "proxyPort"; // port
const spSwitchProxy = "switchProxy"; // 开关代理
bool setProxyFlag = false; // 设置代理标识 true 设置 false 不设置

/// dio 设置代理uri
void setProxyUri(Dio? dio, bool isProdEnv) {
  setProxyFlag = !isProdEnv; //生产环境不设置代理
  if (!setProxyFlag) return;
  String? proxyIP = SpUtil.getString(spProxyIp);
  String? proxyPort = SpUtil.getString(spProxyPort);

  (dio?.httpClientAdapter as IOHttpClientAdapter?)?.createHttpClient = () {
    HttpClient client = HttpClient();
    // 是否设置代理：非生产环境，开启代理后，设置代理
    bool isSetProxy = setProxyFlag &&
        proxyIP != null &&
        proxyIP.isNotEmpty &&
        proxyPort != null &&
        proxyPort.isNotEmpty &&
        SpUtil.getBool(spSwitchProxy) == true;
    if (isSetProxy) {
      client.findProxy = (uri) => "PROXY $proxyIP:$proxyPort";
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
    }
    return client;
  };
}

/// 设置代理widget
setProxyWidget(context) {
  return (!setProxyFlag)
      ? Container()
      : InkWell(
          onTap: () => setProxyDialog(context),
          child: Container(
            height: 50.0,
            padding: const EdgeInsets.only(left: 15.0, right: 15.0),
            color: Colors.white,
            margin: const EdgeInsets.only(top: 1.0),
            child: const Row(
              children: <Widget>[
                Expanded(
                  child: Text("设置代理", style: TextStyle(fontSize: 15.0)),
                ),
                Icon(Icons.arrow_forward_ios, color: Colors.grey, size: 16.0)
              ],
            ),
          ),
        );
}

var ipController = TextEditingController();
var portController = TextEditingController();

/// 设置代理dialog
setProxyDialog(context) {
  ipController.text = SpUtil.getString(spProxyIp) ?? "";
  portController.text = SpUtil.getString(spProxyPort) ?? "";
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return SimpleDialog(
        title: const Text("设置代理", textAlign: TextAlign.center),
        children: [
          _textFieldItem(title: "IP地址:", controller: ipController),
          _textFieldItem(title: "端\t\t\t\t口:", controller: portController),
          Row(
            children: [
              const SizedBox(width: 20.0),
              const Text("开启代理："),
              const Spacer(),
              Builder(builder: (context) {
                return Switch(
                    activeColor: Colors.blue,
                    activeTrackColor: Colors.grey,
                    inactiveThumbColor: Colors.blue,
                    inactiveTrackColor: Colors.grey,
                    value: SpUtil.getBool(spSwitchProxy) ?? false,
                    onChanged: (bool value) {
                      SpUtil.putBool(spSwitchProxy, value);
                      (context as Element).markNeedsBuild();
                    });
              }),
              const SizedBox(width: 20.0),
            ],
          ),
          InkWell(
            onTap: () {
              if (!_checkInfo()) {
                return;
              }
              SpUtil.putString(
                  spProxyIp, ipController.value.text.toString().trim());
              SpUtil.putString(
                  spProxyPort, portController.value.text.toString().trim());
               // 延迟1s 退出，修复保存失败问题
              Future.delayed(const Duration(seconds: 1), () {
                exit(0);
              });

            },
            child: Container(
              margin: const EdgeInsets.only(
                  left: 30.0, right: 30.0, top: 30.0, bottom: 15.0),
              padding: const EdgeInsets.symmetric(vertical: 12.0),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.circular(50.0),
              ),
              alignment: Alignment.center,
              child: const Text("确定", style: TextStyle(color: Colors.white)),
            ),
          )
        ],
      );
    },
  );
}

///校验信息
bool _checkInfo() {
  String ip = ipController.value.text.toString().trim();
  String port = portController.value.text.toString().trim();
  bool setProxy = SpUtil.getBool(spSwitchProxy) ?? false;
  if (!setProxy) return true;
  if (ip.isEmpty) {
    ToastUtil.showToast("请输入ip地址");
    return false;
  }
  if (port.isEmpty) {
    ToastUtil.showToast("请输入端口号");
    return false;
  }
  return true;
}

/// ip、端口 输入框
Widget _textFieldItem({title, controller}) {
  return Container(
    padding: const EdgeInsets.symmetric(horizontal: 20.0),
    margin: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
    decoration: BoxDecoration(
      border: Border.all(color: Colors.grey.shade300),
    ),
    child: Row(
      children: <Widget>[
        Text(title, style: const TextStyle(fontSize: 15.0)),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.only(left: 5.0),
            child: TextField(
              maxLines: 1,
              controller: controller,
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
              decoration: const InputDecoration(
                counterText: "",
                border: InputBorder.none, //去掉下划线
              ),
            ),
          ),
        ),
      ],
    ),
  );
}
